//
//  SDQuestionnaireViewController.m
//  skinDetection
//
//  Created by  liangzhun on 2018/10/31.
//  Copyright © 2018年  liangzhun. All rights reserved.
//

#import "SDQuestionnaireViewController.h"
#import "SDQuestionnaireCell.h"
#import "SDQuestionnaireTabHeaderView.h"
#import "SDQuestionnaireSecHeaderView.h"

#import "SDQuestionAndAnswerModel.h"
#import "SDQuestionAndAnswerData.h"

#import "SDDetectionViewController.h"
#import "SDDetectionReportVC.h"

#import "SDSDQuestionnaireAlertView.h"

#import "SDAnswerTestData.h"
#import "SDAnswerTestSubjectList.h"
#import "SDAnswerTestOptionList.h"
#import "SDAnswersDetectionModel.h"
static NSString *const cellIden = @"SDQuestionnaireCell";
static NSString *const secHeadIden = @"SDQuestionnaireSecHeaderView";

@interface SDQuestionnaireViewController ()<UITableViewDelegate,UITableViewDataSource>

//@property (nonatomic ,strong) SDQuestionAndAnswerModel *model;//问题答案数据模型
@property (nonatomic ,strong) NSMutableArray *dataArray;

@property (nonatomic ,strong) SDQuestionnaireTabHeaderView *tabHeaderView;

@property (nonatomic ,strong) UIView *tabFooterView;

@property (nonatomic ,assign) CGFloat sorce;//总分数

@property (nonatomic ,strong) UIButton *goBtn;//查看报告按钮

@property (nonatomic ,strong) SDSDQuestionnaireAlertView *alert;//提示框

@property (nonatomic ,assign) int progress;//正在答第几题

@property (nonatomic ,strong) SDQuestionAndAnswerData *nowData;//问题答案

@end

@implementation SDQuestionnaireViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    _navHeight.constant = SDNavBar_Height;
    
    [self setTableview];
    [self getData];
    [self setTabHeaderView];
    
    
}
- (void)setTabHeaderView
{
    [self.tabHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(self.tableView.mas_top);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(93);
        
    }];
    self.tabTop.constant = 93;
    
}
- (void)setTableview
{
    self.tableView.estimatedRowHeight = 30;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedSectionHeaderHeight = 36;
    
    [self.tableView registerNib:[UINib nibWithNibName:cellIden bundle:nil] forCellReuseIdentifier:cellIden];
    [self.tableView registerNib:[UINib nibWithNibName:secHeadIden bundle:nil] forHeaderFooterViewReuseIdentifier:secHeadIden];
    self.tableView.tableFooterView = self.tabFooterView;
    
    //添加侧滑手势
    UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(doSwipe:)];
    leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
    
    UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(doSwipe:)];
    rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
    
    for (UIGestureRecognizer *gesture in self.tableView.gestureRecognizers) {
        [self.tableView removeGestureRecognizer:gesture];
    }
    
    [self.tableView addGestureRecognizer:leftSwipe];
    [self.tableView addGestureRecognizer:rightSwipe];
    
}
//获取问卷的问题选择答案数据
- (void)getData
{
    self.dataArray = [[NSMutableArray alloc] initWithCapacity:0];
    SDAnswerTestData *data = [SDAnswersDetectionModel shareInstance].dataArray[[SDAnswersDetectionModel shareInstance].answerTestType - 1];
    [self.titleLab setText:data.title];
    
    for (int d = 0; d < data.subjectList.count; d++) {
        SDAnswerTestSubjectList *list = data.subjectList[d];
        SDQuestionAndAnswerData *dataQ = [[SDQuestionAndAnswerData alloc] init];
        dataQ.question = list.desc;
        NSMutableArray *arrayAnswer = [[NSMutableArray alloc] initWithCapacity:0];
        for (SDAnswerTestOptionList *answer in list.optionList) {
            if (answer.option.length > 0)[arrayAnswer addObject:answer.option];
        }
        dataQ.answers = arrayAnswer;
        [self.dataArray addObject:dataQ];
    }
    
//    //获取问题答案的json串
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"QuestionAndAnswer" ofType:@"txt"];
//    NSData *data = [NSData dataWithContentsOfFile:path];
//    NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    self.model = [SDQuestionAndAnswerModel modelObjectWithDictionary:[SDNetwork jsonStringToDic:jsonStr]];
    
    self.progress = 1;
    
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    SDQuestionnaireCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIden];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5.f;
    NSString *answer = self.nowData.answers[indexPath.row];
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:answer attributes:@{NSParagraphStyleAttributeName:style}];
    [cell.contentLab setAttributedText:att];
    NSString *image = [self.nowData.select isEqualToString:[answer substringToIndex:1]]? @"选中 拷贝":@"椭圆 2";
    //根据选择的答案显示颜色
    UIColor *textColor =[self.nowData.select isEqualToString:[answer substringToIndex:1]]? SDMainColor:SDMainGrayColor;
    [cell.contentLab setTextColor:textColor];
    [cell.selectOrNotImage setImage:[UIImage imageNamed:image]];
    return cell;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.nowData.answers.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    SDQuestionnaireSecHeaderView *secHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:secHeadIden];
     SDQuestionAndAnswerData *data = self.nowData;
    NSString *strQuestLast = [data.question componentsSeparatedByString:@"."].lastObject;
    NSString *strQuest = [NSString stringWithFormat:@"%d/%lu%@",self.progress,(unsigned long)self.dataArray.count,strQuestLast];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5.f;
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:strQuest attributes:@{NSParagraphStyleAttributeName:style}];
    [att addAttribute:NSForegroundColorAttributeName value:RGBA(163, 161, 162, 1) range:NSMakeRange(0, strQuest.length - strQuestLast.length)];
     [att addAttribute:NSForegroundColorAttributeName value:RGBA(207, 104, 255, 1) range:NSMakeRange(0, [NSString stringWithFormat:@"%d",self.progress].length)];

    [secHeaderView.titleLab setAttributedText:att];
    [secHeaderView.titleLab sizeToFit];
    return secHeaderView;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    SDQuestionAndAnswerData *data = self.nowData;
    NSString *answer = self.nowData.answers[indexPath.row];
    data.select = [answer substringToIndex:1];
     [self.tableView reloadData];
     self.goBtn.hidden  = !([self isSelectAll]&&(self.progress == self.dataArray.count));
    if (self.progress < (int)self.dataArray.count) {
        
        //延迟跳转
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)0.1*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            self.progress = self.progress + 1;
            [self Animation:YES view:self.tableView];
        });
        
    }
    
    
}
-(void)setProgress:(int)progress
{
    _progress = progress;
    
    self.nowData = self.dataArray[self.progress - 1];
    self.tabHeaderView.progressLine.constant = (self.progress*1.000/self.dataArray.count)*SDMainScreenWidth;
    self.goBtn.hidden  = !([self isSelectAll]&&(self.progress == self.dataArray.count));
    [self.tableView reloadData];
    
}

- (void)doSwipe:(UISwipeGestureRecognizer *)swipe
{
    if (swipe.direction == UISwipeGestureRecognizerDirectionLeft) {
        
        if (self.progress == (int)self.dataArray.count)return;
        if (self.nowData.select.length == 0)return;
        self.progress = self.progress + 1;
        [self Animation:YES view:self.tableView];
        
    }
    else if (swipe.direction == UISwipeGestureRecognizerDirectionRight)
    {
        
        if (self.progress == 1)return;
        self.progress = self.progress - 1;
        [self Animation:NO view:self.tableView];
        
    }
    
   
   
    
}
- (void)Animation:(BOOL)direction view:(UIView *)view
{
    //动画效果
    CATransition *animation = [CATransition animation];
    
    animation.duration = 0.75f;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.fillMode = kCAFillModeForwards;
    animation.type = kCATransitionPush;
    if (direction) {//左滑
        animation.subtype = kCATransitionFromRight;
    }
    else
    {
        animation.subtype = kCATransitionFromLeft;
    }
    [view.layer addAnimation:animation forKey:@"animation"];
    
}
#pragma mark - lazy加载
-(SDQuestionnaireTabHeaderView *)tabHeaderView
{
    if (!_tabHeaderView) {
        
       _tabHeaderView = [SDMethodTool getViewWithViewName:NSStringFromClass([SDQuestionnaireTabHeaderView class])];
        [self.view addSubview:_tabHeaderView];
        
    }
    
    return _tabHeaderView;
}
-(UIView *)tabFooterView
{
    if (!_tabFooterView) {
        
        _tabFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SDMainScreenWidth, 140)];
        
        self.goBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.goBtn.layer.cornerRadius = 5.f;
        self.goBtn.layer.masksToBounds = YES;
        self.goBtn.hidden = YES;
        [self.goBtn setBackgroundColor:SDMainColor];
        NSString *title = self.isFromDetection? QuestionnaireFotterTitle1:QuestionnaireFotterTitle2;
        [self.goBtn setTitle:title forState:UIControlStateNormal];
        [self.goBtn setFrame:CGRectMake(33, 48, SDMainScreenWidth - 66, 45)];
        [self.goBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
        
            [self getResult];
            
        }];
        [_tabFooterView addSubview:self.goBtn];
        
    }
   
    return _tabFooterView;
    
}
- (void)getResult
{
    
    SDAnswerTestData *data = [SDAnswersDetectionModel shareInstance].dataArray[[SDAnswersDetectionModel shareInstance].answerTestType - 1];
    
    NSLog(@"JJJKKKKKKK%@+%lu",[self getAnswers],(unsigned long)self.dataArray.count);
    [SDNetwork getQuestionResultWithID:data.id Answer:[self getAnswers] Finish:^(NSDictionary * _Nullable dic, NSError * _Nullable error) {
        if (!error&&self.block){
            
            self.block(dic[@"data"]);
            [self back:nil];
            
        }
        
    }];
    
}
////上传测试的皮肤类型
//- (void)upLoadSkinType
//{
//    [SDNetwork getQuestionSurveyWithSkinTypeId:[self getSkinType] Finish:^(NSDictionary * _Nullable dic, NSError * _Nullable error) {
//
//        if (!error) {
//            NSMutableDictionary *userDic = [NSMutableDictionary dictionaryWithDictionary:USERDEFAULT_GET(KEY_USERMSG)];
//            [userDic setObject:[NSNumber numberWithInt:[self getSkinType]] forKey:@"skinType"];
//            USERDEFAULT_PUT(userDic, KEY_USERMSG);
//            SDAppDelegate.userModel = [SDUserInformationModel modelObjectWithDictionary:USERDEFAULT_GET(KEY_USERMSG)];
//            self.isFromDetection?[self createReport]:[self.navigationController popViewControllerAnimated:YES];
//            if (self.block)self.block();
//
//        }
//
//    }];
//
//}

////根据分数来判断用户的皮肤类型
//- (skinTypeDO)getSkinType
//{
//    return  self.sorce <= 16 ? skinTypeDO_Much_D:self.sorce <= 26 ? skinTypeDO_Little_D:self.sorce <= 33 ? skinTypeDO_Little_O:skinTypeDO_Much_O;
//}

- (NSString *)getAnswers
{
    NSString *answer = @"";
    for (int s = 0; s < self.dataArray.count; s++) {
        
         SDQuestionAndAnswerData *data = self.dataArray[s];
      answer = answer.length == 0? data.select:[NSString stringWithFormat:@"%@,%@",answer,data.select];
    }
    return answer;
    
}

///**
// 生成检测报告
// */
- (void)createReport
{
    [SDNetwork postGenerateReportFinish:^(NSDictionary * _Nullable dic, NSError * _Nullable error) {
        // LogString([SDNetwork dicToJSONWith:dic]);
        
        if (!error) {
            SDDetectionReportVC *vc = [SDMethodTool getViewControlWithIdentifier:NSStringFromClass([SDDetectionReportVC class])];
            vc.reportId = [dic[@"data"] intValue];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];
    
}

///**
// 问卷调查是否做完
//
// @return YES NO
// */
- (BOOL)isSelectAll
{

    for (int s = 0; s < self.dataArray.count; s ++) {

        SDQuestionAndAnswerData *data = self.dataArray[s];
        
        if (data.select.length == 0) {
            return NO;
        }

    }

    return YES;

}

///**
// 皮肤类型确认警告框
// */
//- (void)showAlertView
//{
//    skinTypeDO skinType = [self getSkinType];
//
//    NSString *content2 = skinType == skinTypeDO_Much_D? Much_D:skinType == skinTypeDO_Much_O? Much_O:skinType == skinTypeDO_Little_D? Little_D:Little_O;
//    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:NSSTRINGAPPEND(alertContentQuestionnaire, content2)];
//    [att addAttribute:NSForegroundColorAttributeName value:SDMainColor range:NSMakeRange(att.length - content2.length, content2.length)];
//    self.alert.contentLab.attributedText = att;
//    self.alert.alpha = 1.0;
//}
-(SDSDQuestionnaireAlertView *)alert
{
    if (!_alert) {
        _alert = [SDMethodTool getViewWithViewName:NSStringFromClass([SDSDQuestionnaireAlertView class])];
        _alert.alpha = 0.0;
        UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAlert)];
        [_alert addGestureRecognizer:ges];
        [_alert.confirmBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
           
          
            self.alert.alpha = 0.0;
            
        }];
        [_alert setUI];
        [self.view addSubview:_alert];
    }
    return _alert;
    
}
//隐藏警告框
- (void)dismissAlert
{
   self.alert.alpha = 0.0;
}
- (IBAction)back:(UIButton *)sender {
     [self.navigationController popViewControllerAnimated:YES];
}
@end
